/**
 * 结构树数据相关处理
 * @module helper/tree.js
 * @author 吴杰
 */

/**
 * 结构树勾选过滤保留父级
 * @param {Array} arr 树返回的结构数据节点 nodes
 * @param {String} key=id node-key 默认 id
 * @param props 树节点配置
 * @returns {Array} 返回 nodes 数组
 */
export function treeFetchParent(arr = [], key = 'id', props = {
  label: 'label',
  children: 'children'
}) {
  const localData = Array.isArray(arr) ? arr : []
  let result = [], arr1 = [], surplus = []
  let treeMap = function (treeMapData) {
    if (treeMapData[props.children]) {
      treeMapData[props.children].map(tr => {
        surplus.push(tr[key])
        treeMap(tr)
      })
    }
  }
  if (localData.length > 0) {
    localData.map(r => {
      arr1.push(r)
      treeMap(r)
    })
    for (let ai = 0; ai < arr1.length; ai++) {
      if (!surplus.includes(arr1[ai][key])) {
        result.push(arr1[ai])
      }
    }
  }
  return result
}

/**
 * 把树结构转换成列表数据, 数据必须有父节点标识
 * @param {array} tree 树结构组对象
 * @param {Object} [prop={children:'children'}] 属性映射, 可选
 * @returns {Array} 返回数组
 */
export function treeToList(tree, prop = {
  children: 'children'
}) {
  let result = []
  if (!tree || tree.length === 0) {
    return result
  }
  // 定义遍历树结构函数
  const eachTree = obj => {
    if (obj && obj.length > 0) {
      obj.forEach(item => {
        result.push(item)
        if (item[prop.children] && item[prop.children].length > 0) {
          eachTree(item[prop.children])
        }
      })
    }
  }
  // 开始遍历
  eachTree(tree)
  return result
}
